package com.imooc.restaurant.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.restaurant.dao.ProductDao;
import com.imooc.restaurant.dao.RestaurantDao;
import com.imooc.restaurant.dto.OrderMessageDTO;
import com.imooc.restaurant.enummeration.ProductStatus;
import com.imooc.restaurant.enummeration.RestaurantStatus;
import com.imooc.restaurant.po.ProductPo;
import com.imooc.restaurant.po.RestaurantPo;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * ProjectName restaurant
 *
 * @author xieyucan
 * <br>CreateDate 2022/9/20 16:48
 */
@Slf4j
@Service
public class OrderMessageService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RestaurantDao restaurantDao;

    ObjectMapper objectMapper=new ObjectMapper();

    @Async
    public void handleMessage() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("43.138.244.235");
        connectionFactory.setPort(5672);
        connectionFactory.setPassword("1234");
        connectionFactory.setUsername("admin");
        try (Connection connection=connectionFactory.newConnection();
             Channel channel=connection.createChannel()){
            channel.exchangeDeclare(
                "exchange.order.restaurant",
                    BuiltinExchangeType.DIRECT,
                    true,
                    false,null
            );
            channel.queueDeclare(
                    "queue.restaurant",
                    true,
                    false,
                    false,
                    null
            );
            channel.queueBind(
                    "queue.restaurant",
                    "exchange.order.restaurant",
                    "key.restaurant"
            );

            channel.basicConsume(
                    "queue.restaurant",
                    true,
                    deliverCallback,
                    consumerTag -> {}
            );
            while (true){
                Thread.sleep(10000000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    DeliverCallback deliverCallback=((consumerTag, message) -> {
        String messageBody = new String(message.getBody());
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("43.138.244.235");
        connectionFactory.setPort(5672);
        connectionFactory.setPassword("1234");
        connectionFactory.setUsername("admin");
        try{
            OrderMessageDTO orderMessageDTO = objectMapper.readValue(messageBody, OrderMessageDTO.class);
            ProductPo productPo = productDao.selectProduct(orderMessageDTO.getProductId());
            System.out.println("jjjjjj");
            RestaurantPo restaurantPo = restaurantDao.selectRestaurant(productPo.getRestaurantId());
           if(productPo.getStatus().equals(ProductStatus.AVALIABLE)&&restaurantPo.getStatus().equals(RestaurantStatus.OPEN))
           {
               orderMessageDTO.setConfirmed(true);
               orderMessageDTO.setPrice(productPo.getPrice());
           } else {
               orderMessageDTO.setConfirmed(false);
           }


           try (Connection connection=connectionFactory.newConnection();
            Channel channel=connection.createChannel()){
                String messageToSend=objectMapper.writeValueAsString(orderMessageDTO);
                channel.basicPublish(
                        "exchange.order.restaurant",
                        "key.order",
                        null,
                        messageToSend.getBytes());
           }
        } catch (TimeoutException e) {
            log.error(e.getMessage(),e);
        }
    });
}
